package com.itheima.nosql.action;

import com.itheima.nosql.entity.Address;
import com.itheima.nosql.entity.Spu;
import com.itheima.nosql.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/api/mongo")
@Api(tags = {"mongo"})
public class MongoController {
    @Autowired
    MongoTemplate template;
    
    /**
     * 添加数据测试mongoDB的索引效果
     */
    @GetMapping("/init")
    @ApiOperation(value = "灌测试数据")
    public void mongo() {
        Random random = new Random();
        for (int i = 0; i < 300; i++) {
            List list = new ArrayList(100);
            for (int j = 0; j < 1000; j++) {
                User user = new User();
                user.setName("用户" + random.nextInt(1000));
                user.setAge(20 + random.nextInt(60));
                user.setTags(User.tags(random));
                list.add(user);
            }
            template.insertAll(list);
            System.out.println("batch " + i);
        }
    }
    
    /**
     * SwaggerConfig
     * mongoDB支持通过球面或者圆来计算距离
     */
    @GetMapping("/geo")
    @ApiOperation(value = "地址测试数据")
    public void geo() {
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            List list = new ArrayList(100);
            for (int j = 0; j < 1000; j++) {
                Address address = new Address(
                        "地址" + (i * 1000 + j),
                        random.nextInt(360) - 180,
                        random.nextInt(180) - 90
                );
                list.add(address);
            }
            template.insertAll(list);
            System.out.println("batch " + i);
        }
    }
    
    /**
     * 查询信息
     * zhz添加的  2021/7/21
     *
     * @return
     */
    @GetMapping("/query")
    @ApiOperation(value = "java查询")
    public Object query2() {
        Aggregation aggregation =
                Aggregation.newAggregation(
                        Aggregation.lookup("sku", "_id", "pid", "sku"),
                        Aggregation.match(Criteria.where("_id").is("1")),
                        Aggregation.project("_id", "name", "sku")
                );
        AggregationResults spu =
                template.aggregate(aggregation, "spu", Spu.class);
        return spu.getMappedResults();
    }
}
